<template>
    <div class="role-list">
        <div class="button-group">
            <el-button type="primary" size="small" icon="el-icon-plus" @click="add" v-if="buttons[$buttonCode.add]">添加</el-button>
        </div>
        <el-table :data="list" stripe>
            <el-table-column prop="id" label="角色ID" width="100"></el-table-column>
            <el-table-column prop="name" label="角色名称"></el-table-column>
            <el-table-column prop="name" label="人数" width="160"></el-table-column>
            <el-table-column label="状态" width="160">
                <template #default="{row}">
                    <el-switch
                        :disabled="!buttons[$buttonCode.updateState]"
                        v-model="row.status"
                        active-color="#13ce66"
                        inactive-color="#ff4949"
                        :active-value="1"
                        :inactive-value="0"
                        @change="updateState(row)"
                    ></el-switch>
                </template>
            </el-table-column>
            <el-table-column label="创建时间">
                <template #default="{row}">
                    {{$formatDate(row.createTime)}}
                </template>
            </el-table-column>
            <el-table-column label="操作" width="200">
                <template #default="{row}">
                    <template v-if="row.id !== -1">
                        <el-button type="text" size="small" @click="edit(row)" v-if="buttons[$buttonCode.update]">编辑</el-button>
                        <el-button type="text" size="small" @click="del(row)" v-if="buttons[$buttonCode.del]">删除</el-button>
                    </template>
                    <el-button type="text" size="small" @click="viewUser(row)" v-if="buttons[$buttonCode.view]">查看成员</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!--<el-pagination
            background
            :current-page="page"
            :page-size="$pageSize"
            layout="prev, pager, next"
            :total="total"
            @current-change="goPage"
        ></el-pagination>-->
        <el-dialog :visible.sync="editVisible" :title="isEdit ? '编辑角色' : '添加角色'">
            <el-form :model="form" :rules="rules" ref="form" label-width="100px" class="demo-form">
                <el-form-item label="角色名称：" prop="name">
                    <el-input v-model="form.name"></el-input>
                </el-form-item>
                <el-form-item label="角色状态：" prop="name">
                    <el-switch
                        v-model="form.status"
                        active-color="#13ce66"
                        inactive-color="#ff4949"
                        :active-value="1"
                        :inactive-value="0"
                    ></el-switch>
                </el-form-item>
                <el-form-item label="权限范围：" prop="menuIds">
                    <el-tree
                        ref="tree"
                        :data="tree"
                        show-checkbox
                        node-key="id"
                        default-expand-all
                        :expand-on-click-node="false"
                        :check-on-click-node="true"
                        :props="defaultProps"
                    ></el-tree>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button size="small" type="primary" :disabled="btnDisabled" @click="save">保存</el-button>
                <el-button size="small" @click="editVisible = false">取消</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script>
import {
    getRoleList,
    updateRole,
    updateRoleState,
    delRole,
    getPermissionList,
    getRoleUsers,
} from '@/api/user';
import mixin from '@/mixins/buttons';

export default {
    name: 'roleList',
    mixins: [mixin],
    data() {
        return {
            list: [],
            page: 1,
            total: 0,
            editVisible: false,
            isEdit: false,
            tree: [],
            form: {
                name: '',
                menuIds: [],
                status: 1,
                remarks: '',
            },
            rules: {
                name: [
                    {required: true, message: '请输入角色名称', trigger: 'blur'},
                ],
                menuIds: [
                    {required: true, message: '请选择权限', trigger: 'blur'},
                ],
            },
            defaultProps: {
                children: 'children',
                label: 'name',
            },
            btnDisabled: false,
        };
    },
    created() {
        this.getRoleList();
        this.getPermissionList();
    },
    methods: {
        getRoleList() {
            getRoleList().then(({data}) => {
                const {list, totalCount} = data;
                this.list = list;
                this.total = totalCount;
            }).catch(err => {
                this.list = [];
                this.total = 0;
            });
        },
        // 分页切换
        goPage(page) {
            this.page = page;
            this.getRoleList();
        },
        // 获取所有权限
        getPermissionList() {
            getPermissionList({
                pId: -1,
            }).then(({data}) => {
                this.tree = data;
            }).catch(err => {
                this.tree = [];
            });
        },
        // 添加
        add() {
            this.isEdit = false;
            this.form = {
                name: '',
                menuIds: [],
                status: 1,
                remarks: '',
            };
            this.editVisible = true;
        },
        // 编辑
        edit(item) {
            this.isEdit = true;
            const {id, name, menuIds, status, remarks} = item;
            this.form = {id, name, menuIds, status, remarks};
            this.editVisible = true;
            if (menuIds && menuIds.length > 0) {
                this.$nextTick(() => {
                    for (let id of menuIds) {
                        this.$refs.tree.setChecked(id, true, false);
                    }
                });
            }
        },
        // 保存
        save() {
            const menus = this.$refs.tree.getCheckedNodes(false, true);
            this.form.menuIds = menus.map(item => item.id);
            this.$refs.form.validate((valid) => {
                if (!valid) {
                    return;
                }
                this.btnDisabled = true;
                updateRole(this.form).then(() => {
                    this.$message.success('保存成功');
                    this.btnDisabled = false;
                    this.getRoleList();
                    this.editVisible = false;
                }).catch(err => {
                    this.btnDisabled = false;
                });
            });
        },
        // 删除
        async del(item) {
            const {id, name} = item;
            try {
                await this.$confirm(`确定要删除角色 ${name} 吗`);
                await delRole({itemIds: [id]});
                this.$message.success('删除角色成功');
                const index = this.list.findIndex(item => item.id === id);
                this.list.splice(index, 1);
            } catch (e) {
                console.log(e);
            }
        },
        // 查看用户
        viewUser(item) {
            const {id, name} = item;
            getRoleUsers({id}).then(({data}) => {
                console.log(data);
            });
        },
        // 修改状态
        updateState(item) {
            const {id, status} = item;
            updateRoleState({id, status}).then(() => {
                this.$message.success(`${status === 1 ? '启用' : '禁用'}角色成功`);
            }).catch(err => {
                item.status = status === 1 ? 0 : 1;
            });
        },
    },
};
</script>

<style scoped lang="less">

</style>
